//
//  UITableViewController+InfiniteScroll.m
//  Pods
//
//  Created by Liu Zhen on 12/22/15.
//
//

#import "UITableViewController+InfiniteScroll.h"
#import "InfiniteScrollControl.h"
#import <JRSwizzle/JRSwizzle.h>

@import ObjectiveC.runtime;

@interface InfiniteScrollControl()
@property (nonatomic) UIEdgeInsets originalInset;
@end

@implementation UITableViewController (InfiniteScroll)

static void *InfiniteScrollControlKey=&InfiniteScrollControlKey;

+ (void)load {
    [[self class] jr_swizzleMethod:@selector(viewDidLoad) withMethod:@selector(swizzle_viewDidLoad) error:nil];
    [[self class] jr_swizzleMethod:@selector(viewWillLayoutSubviews) withMethod:@selector(swizzle_viewWillLayoutSubviews) error:nil];
}

- (InfiniteScrollControl *)infiniteScrollControl {
    return objc_getAssociatedObject(self, InfiniteScrollControlKey);
}

- (void)setInfiniteScrollControl:(InfiniteScrollControl *)infiniteScrollControl {
    objc_setAssociatedObject(self, InfiniteScrollControlKey, infiniteScrollControl, OBJC_ASSOCIATION_RETAIN);
}

void *InfiniteScrollKey = &InfiniteScrollKey;

- (void)setInfiniteScroll:(BOOL)infiniteScroll {
    objc_setAssociatedObject(self, InfiniteScrollKey, @(infiniteScroll), OBJC_ASSOCIATION_RETAIN);
    
    if(infiniteScroll && !self.infiniteScrollControl) {
        InfiniteScrollControl *control = [[InfiniteScrollControl alloc] init];
        self.infiniteScrollControl = control;
    }
}

- (BOOL)infiniteScroll {
    return [objc_getAssociatedObject(self, InfiniteScrollKey) boolValue];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (!self.tableView.isDragging &&
        !self.infiniteScrollControl.isLoading &&
        self.tableView.contentOffset.y + self.tableView.frame.size.height >= self.tableView.contentSize.height - 2) {
        [self.infiniteScrollControl beginRefreshing];
    }
}

- (void)swizzle_viewDidLoad {
    [self swizzle_viewDidLoad];
    
    //显示底部加载
    if (self.infiniteScrollControl) {
        self.infiniteScrollControl.originalInset = self.tableView.contentInset;
        UIEdgeInsets inset = self.infiniteScrollControl.originalInset;
        inset.bottom += 44;
        self.tableView.contentInset = inset;
        self.infiniteScrollControl.controller = self;
        [self.tableView addSubview:self.infiniteScrollControl];
    }
}

- (void)swizzle_viewWillLayoutSubviews {
    [self swizzle_viewWillLayoutSubviews];
    self.infiniteScrollControl.frame = CGRectMake(0, self.tableView.contentSize.height, self.tableView.frame.size.width, 44);
}

@end
